<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="检验单编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入检验单编码"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验单名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入检验单名称"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检验单类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择检验单类型"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.dictCode"
            :label="item.dictValue"
            :value="item.dictCode"
          >
            <span style="float: left">{{ item.dictCode }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dictValue }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['quality:invoices:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['quality:invoices:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['quality:invoices:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['quality:invoices:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="invoicesList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="60" align="center" fixed="left" />
      <el-table-column label="检验单组件id" align="center" width="100" fixed="left" prop="id" v-if="false" />
      <el-table-column label="检验单编码" align="center" prop="code" width="140" fixed="left" />
      <el-table-column label="检验单名称" align="center" prop="name" width="200" />
      <el-table-column label="物料名称" align="center" prop="materialName" width="200" />
      <el-table-column label="质检标准名称" align="center" prop="criterionName" width="200" />
      <el-table-column label="检验单类型" align="center" prop="typeName" width="140" />
      <el-table-column label="状态" align="center" prop="status" width="100" :formatter="getStatusName" />
      <el-table-column label="工单" align="center" prop="workOrderNumber" width="100" />
      <!-- <el-table-column label="检验单结果" align="center" prop="result" width="140" /> -->
      <el-table-column label="工位" align="center" prop="stationName" width="100" />
      <el-table-column label="备注" align="center" prop="remark" width="200" />
      <el-table-column label="检验完成时间" align="center" prop="finishTime" width="160" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="创建人" align="center" prop="createUserName" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            style="margin-right: 9px"
            @click="handleDetail(scope.row)"
            v-hasPermi="['quality:invoices:detail']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['quality:invoices:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加质检单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="12">
            <el-form-item label="检验单编码" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入检验单编码"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="检验单名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入检验单名称"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="检验单类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择检验单类型"
                style="width: 240px"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.dictCode"
                  :label="item.dictValue"
                  :value="item.dictCode"
                >
                  <span style="float: left">{{ item.dictCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dictValue }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="物料名称" prop="materialId">
              <el-select
                v-model="form.materialId"
                placeholder="请选择物料名称"
                style="width: 240px"
              >
                <el-option
                  v-for="item in materialList"
                  :key="item.materialId"
                  :label="item.materialName"
                  :value="item.materialId"
                >
                  <span style="float: left">{{ item.materialId }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="质检标准" prop="criterion">
              <el-select
                v-model="form.criterion"
                placeholder="请选择质检标准"
                style="width: 240px"
              >
                <el-option
                  v-for="item in criterionOptions"
                  :key="item.dictCode"
                  :label="item.dictValue"
                  :value="item.dictCode"
                >
                  <span style="float: left">{{ item.dictCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dictValue }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="工位" prop="station">
              <el-select
                v-model="form.station"
                placeholder="请选择工位"
                style="width: 240px"
              >
                <el-option
                  v-for="item in treeGWOptions"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
                >
                  <span style="float: left">{{ item.shopId }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.shopName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="工单" prop="workOrderNumber">
              <el-input
                v-model="form.workOrderNumber"
                placeholder="请输入工单"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入备注"
                style="width: 240px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 质检单详情对话框 -->
    <el-dialog title="质检详情" :visible.sync="detailOpen" width="760px" append-to-body>
      <div style="height: 380px; overflow-y: auto;">
        <div style="padding: 0px 0px 20px 10px">
          <span>检验结论：</span>
          <el-radio-group v-model="detailForm.status">
            <el-radio :label="0">未检验</el-radio>
            <el-radio :label="1">不合格</el-radio>
            <el-radio :label="2">合格</el-radio>
          </el-radio-group>
        </div>
        <el-table
          v-loading="detailLoading"
          :data="detailList"
        >
          <el-table-column label="检验单组件id" align="center" prop="id" v-if="false" />
          <el-table-column label="检验单名称" align="center" prop="checkName" />
          <el-table-column label="检验状态" align="center" width="300">
            <template slot-scope="scope">
              <el-radio-group v-model="detailForm[`status_${scope.row.id}`]">
                <el-radio :label="0">未检验</el-radio>
                <el-radio :label="1">不合格</el-radio>
                <el-radio :label="2">合格</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="缺陷类型" align="center" width="240">
            <template slot-scope="scope">
              <el-select
                v-model="detailForm[`typeId_${scope.row.id}`]"
                placeholder="请选择检验单类型"
                style="width: 200px"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.dictCode"
                  :label="item.dictValue"
                  :value="item.dictCode"
                >
                  <span style="float: left">{{ item.dictCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dictValue }}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailSubmitForm">确 定</el-button>
        <el-button @click="detailCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listInvoices,
    getInvoices,
    getInvoicesAll,
    upDataInvoices,
    delInvoices,
    addInvoices,
    exportInvoices,
  } from "@/api/quality/invoices";
  import { listMaterial } from "@/api/base/material";
  import { getTree } from "@/api/pull/feedSet";

  export default {
    name: "Invoices",
    data() {
      return {
        // 遮罩层
        loading: true,
        detailLoading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 物料下拉框
        materialList: [],
        // 检验单类型下拉框
        typeOptions: [],
        // 质检标准下拉框
        criterionOptions: [],
        // 工位下拉框
        treeGWOptions: [],
        // 质检单表格数据
        invoicesList: [],
        // 质检单详情表格数据
        detailList: [],
        // 质检单详情状态
        radio: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        detailOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          code: undefined,
          name: undefined,
          type: undefined,
          
        },
        // 表单参数
        form: {},
        detailForm: { status: 0 },
        // 表单校验
        rules: {
          code: [{ required: true, message: "检验单编码不能为空", trigger: "change" }],
          name: [{ required: true, message: "检验单名称不能为空", trigger: "change" }],
          type: [{ required: true, message: "检验单类型不能为空", trigger: "change" }],
          materialId: [{ required: true, message: "物料名称不能为空", trigger: "change" }],
          criterion: [{ required: true, message: "质检标准不能为空", trigger: "change" }],
          station: [{ required: true, message: "工位不能为空", trigger: "change" }],
          workOrderNumber: [{ required: true, message: "工单不能为空", trigger: "change" }]
        }
      };
    },
    created() {
      this.getMaterialList();
      this.getTreeGW();
      this.getList();
      // 数据字段
      this.getDicts("receipts_type").then((response) => {
        this.typeOptions = response.data;
      });
      this.getDicts("criterion").then((response) => {
        this.criterionOptions = response.data;
      });
    },
    methods: {
      /** 查询质检单列表 */
      getList() {
        this.loading = true;
        listInvoices(this.queryParams).then(response => {
          this.invoicesList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 物料树
      getMaterialList() {
        listMaterial({}).then((response) => {
          this.materialList = response.rows;
        });
      },
      // 查询工位树
      getTreeGW() {
        getTree(4).then(response => {
          // const newData = this.getTreeData(response.data);
          this.treeGWOptions = response.data;
        });
      },
      // 状态
      getStatusName(row, column) {
        let name = '';
        switch(row.status) {
          case 0:
            name = '未检验'
            break;
          case 1:
            name = '不合格'
            break;
          case 2:
            name = '合格'
            break;
          default: console.log("no default")
        }
        return name;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 详情取消按钮
      detailCancel() {
        this.detailOpen = false;
        this.detailList = [];
        this.detailForm = { status: 0 };
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加质检单";
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            addInvoices(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        });
      },
      /** 详情提交按钮 */
      detailSubmitForm() {
        const arr = [];
        this.detailList.map((item, index) => {
          const obj = {};
          obj.id = item.id;
          obj.status = this.detailForm[`status_${item.id}`];
          obj.typeId = this.detailForm[`typeId_${item.id}`];
          arr.push(obj);
        });
        upDataInvoices(arr, this.detailForm.status, this.detailList[0]?.receiptsId).then(response => {
          if (response.code === 200) {
            this.msgSuccess("检验单任务提交成功");
            this.detailOpen = false;
            this.detailList = [];
            this.detailForm = { status: 0 };
            this.getList();
          }
        });
      },
      // 详情按钮操作
      handleDetail(row) {
        this.detailLoading = true;
        const invoicesIds = row.id || this.ids; 
        const obj = {};
        getInvoicesAll(invoicesIds).then(response => {
          response.rows.map((item, index) => {
            obj.status = row.status;
            obj[`status_${item.id}`] = item.status;
            obj[`typeId_${item.id}`] = item.typeId;
          });
          this.detailList = response.rows;
          this.detailForm = obj;
          this.detailLoading = false;
          this.detailOpen = true;
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const invoicesIds = row.id || this.ids;
        this.$confirm('是否确认删除质检单编号为"' + invoicesIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInvoices(invoicesIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有质检单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportInvoices(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
